import { TodoList, IAction, Actions, Todo, ID } from "./types";

type TodoReducer = React.Reducer<TodoList, IAction>;

export const reducer: TodoReducer = (state, { type, payload }) => {
  switch (type) {
    case Actions.FETCH_TODO_LIST:
      console.log("init:", payload);

      return payload as TodoList;
    case Actions.ADD_TODO:
      return [...state, payload as Todo];
    case Actions.REMOVE_TODO:
      return state.filter((todo: Todo) => todo._id !== (payload as ID));
    case Actions.TOGGLE_TODO_STATUS: {
      const temp = [...state];
      temp.some((todo: Todo) => {
        if (todo._id === payload) {
          // todo.status = !todo.status;
          // TODO 传入状态
          todo.status = true;
          console.log(todo);
          return true;
        }
        return false;
      });
      return temp;
    }
    default:
      return state;
  }
};
